from smap.driver import SmapDriver
from smap.util import periodicSequentialCall
import calendar
from dateutil import tz
from datetime import datetime
import os
import xlrd
import sys

class oldHoboDriver(SmapDriver):
	
	def setup(self, opts):
		folder = '/home/dheinzerling/BSG/bsg on 169.229.130.74/!Projects/HVAC/UFAD/NSA - 2012/Data/HOBO/Plenum/old hobos/'
		self.ids = {}
		self.data = {}
		for filename in os.listdir(folder):
			f = xlrd.open_workbook(folder + filename)
			dataName = filename[:6]
			data = f.sheet_by_index(0)
			datetimes = data.col_values(0)[1:]
			values = data.col_values(1)[1:]
			self.data[dataName] = [datetimes,values]
			print len(self.data[dataName][0])
			if len(self.data[dataName][0]) > 0:
				ts = self.add_timeseries('/%s' % dataName + '_temp', 'F', data_type="double")
				self.ids[dataName] = ts['uuid']
			else:
				del self.data[dataName]
					
		self.period = opts.get("Period", 1000000)

	def start(self):
		periodicSequentialCall(self.read).start(self.period)
	
	def read(self):
		time_zone = tz.gettz('America/New_York')
		for dataName in self.data:
			print dataName
			errorCount = 0
			for i in xrange(len(self.data[dataName][0])):
				try:
					dttime = self.data[dataName][0][i]
					point_date = datetime.strptime(dttime, '%m/%d/%y %H:%M:%S.0').replace(tzinfo = time_zone)
					smaptime = calendar.timegm(point_date.utctimetuple())
				except:
					print "Unexpected error:", sys.exc_info()[0]
					continue
				try:
					value = self.data[dataName][1][i]
					self.add(self.ids[dataName], smaptime, float(value))
						
				except ValueError:
					errorCount += 1
			print errorCount
